import axios from 'axios'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  timeout: 30000 // 超时时间
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['token'] = getToken()
    if (config.data && config.data.$_isFormData) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
      config.data = config.data.formData
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  }
)

// request拦截器
service.interceptors.response.use(
  (res) => {
    const isBlob = res.config.responseType && res.config.responseType === 'blob'
    if (res.data.code === 20000 || isBlob) {
      return res.data
    } else {
      if (res.data.code === 99999 && process.env.ENV !== 'development') {
        window.location.href = `${process.env.VUE_APP_BASE_API}`
      } else {
        MessageBox({
          message: res.data.msg,
          type: 'error',
          duration: 5 * 1000,
          customClass: 'el-message-box-err'
        })
      }
      return Promise.reject('error')
    }
  },
  (error) => {
    console.log('err' + error)
    MessageBox({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
      customClass: 'el-message-box-err'
    })
    return Promise.reject(error)
  }
)

export default service
